package com.example.testsbjenkins.zipFiles;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import org.apache.commons.compress.archivers.zip.ParallelScatterZipCreator;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.parallel.InputStreamSupplier;
import org.apache.commons.io.input.NullInputStream;
import org.springframework.util.StopWatch;

import java.io.*;
import java.util.concurrent.*;

/**
 * @author: lt
 * @date: 2022/7/15 17:34
 * @Description: todo
 */
public class Test {
    /**
     * @param sourceFilePath 需要压缩的目录
     * @param zipOutName 压缩后的文件名称
     **/
    public static void compressFileList(String sourceFilePath, String zipOutName) throws IOException, ExecutionException, InterruptedException {
        StopWatch watch = new StopWatch();
        watch.start();
        File sourceFile = new File(sourceFilePath);
        File[] sourceFiles = sourceFile.listFiles();
        ThreadFactory factory = new ThreadFactoryBuilder().setNamePrefix("compressFileList-pool-").build();
        ExecutorService executor = new ThreadPoolExecutor(50, 200, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(100), factory);
        ParallelScatterZipCreator parallelScatterZipCreator = new ParallelScatterZipCreator(executor);
        OutputStream outputStream = new FileOutputStream(zipOutName);
        ZipArchiveOutputStream zipArchiveOutputStream = new ZipArchiveOutputStream(outputStream);
        zipArchiveOutputStream.setEncoding("UTF-8");
        for (File inFile : sourceFiles) {
            final InputStreamSupplier inputStreamSupplier = () -> {
                try {
                    return new FileInputStream(inFile);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    return new NullInputStream(0);
                }
            };
            ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(inFile.getName());
            zipArchiveEntry.setMethod(ZipArchiveEntry.DEFLATED);
            zipArchiveEntry.setSize(inFile.length());
            zipArchiveEntry.setUnixMode(UnixStat.FILE_FLAG | 436);
            parallelScatterZipCreator.addArchiveEntry(zipArchiveEntry, inputStreamSupplier);
        }
        parallelScatterZipCreator.writeTo(zipArchiveOutputStream);
        zipArchiveOutputStream.close();
        outputStream.close();
        watch.stop();
        System.out.println("耗时:"+watch.getTotalTimeMillis());
    }



    public static void main(String[] args) throws InterruptedException, ExecutionException, IOException {
        compressFileList("C:\\Users\\Administrator.DESKTOP-4PCK80Q\\Desktop\\test\\2\\t\\","C:\\Users\\Administrator.DESKTOP-4PCK80Q\\Desktop\\test\\zip\\1.zip");
    }
}
